import {Table, Tooltip, Form, Input, Row, Button, Col} from 'antd';
// import Table from '../../../_antd1.11.2/table'
// import Tooltip from '../../../_antd1.11.2/tooltip'
// import Form from '../../../_antd1.11.2/form'
// import Input from '../../../_antd1.11.2/input'
// import Row from '../../../_antd1.11.2/row'
// import Col from '../../../_antd1.11.2/col'
// import Button from '../../../_antd1.11.2/button'
const FormItem = Form.Item;
const createForm = Form.create;

import * as API from './api'

//import 'fetch-polyfill'

//import 'whatwg-fetch-ie8';
//import 'fetch-ie8'

// const getFd = (values) => {
// 	let fd = "";
// 	//var data = new FormData();
// 	for(let p in values) {
// 		fd += p+"="+values[p]+"&";
// 		//data.append(p,values[p]);
// 	}
// 	return fd;
// }

// function doDatasGet(url,params) {
// 	return new Promise(function(resolve) {
// 		fetch(url,{
//             method: 'post',
//             headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'},
//             credentials: 'include',
//             body: params
//             //body: JSON.stringify(data)
//         }).then(function(response) {
//             //console.log("data:",data);
//             //console.log("response.json():",response);
//             resolve(response.json());
//         }).catch(function(ex) {
//             resolve([]);
//             console.log('parsing failed', ex);
//         });
// 		// jQuery.ajax({
// 		//     type:"POST",
// 		//     url:url,
// 		//     data:params,
// 		//     success(datas) {
// 		//         resolve(datas);
// 		//     },
// 		//     error(datas) {
// 		//     	resolve([]);
// 		//     },
// 		//     dataType: "json"
// 		// });
// 	});
// }

class WeaList extends React.Component {
	constructor(props) {
		super(props);
		// console.log("WeaList:",props);
		this.state = {
			searchs: [],
			datas: [],
			columns: [],
			count: 0,
			toPage: 1,
			loading: true,
			ids: new Array(),
			names: new Array(),
			pageSize: 10,
			dataKey: "",
			title: "",
			isMain: true,
			params: [],
			rowKey:'',
		}
	}
	componentWillReceiveProps(nextProps) {
		const {ids, names,fieldhtmltype, type, fielddbtype, fieldId} = this.props;
		const nextIds = nextProps.ids;
		const nextNames = nextProps.names;
		const params = { fieldhtmltype, type, fielddbtype, fieldId };
		if (ids != nextIds) {
    		this.setState({
				ids: nextIds ? nextIds.split(",") : new Array(),
				names: nextNames ? nextNames.split(",") : new Array()
    		});
		}
		!this.props.visible && nextProps.visible && this.getDatas(1, params, true);
		this.props.visible && !nextProps.visible && this.setState({isMain:true});
	}
	componentDidUpdate(prevProps,prevState){
		const {fieldhtmltype, type, fielddbtype, fieldId} = this.props;
		const params = { fieldhtmltype, type, fielddbtype, fieldId };
		this.state.pageSize !== prevState.pageSize && this.getDatas(1, params, true);

	}
	componentDidMount() {
		const {fieldhtmltype, type, fielddbtype, fieldId} = this.props;
		const params = { fieldhtmltype, type, fielddbtype, fieldId };
		this.getDatas(1, params, true);
	}
	getDatas(toPage, params, needCount) {
		let that = this;
		const {countUrl, listUrl, paramsUrl, datasType, id, keyNum, dn} = this.props;
		//console.log("countUrl:",countUrl);
		const {pageSize, searchs} = this.state;
		const newMin = (toPage - 1) * pageSize + 1;
		const newMax = toPage * pageSize;

		let newParams = "min=" + newMin + "&max=" + newMax;
		//let newParams = "fieldhtmltype=" + params.fieldhtmltype + "&type=" + params.type + "&fielddbtype=" + params.fielddbtype + "&fieldId=" + params.fieldId + "&min=" + newMin + "&max=" + newMax;
		if (datasType == "request") newParams += "&requestname=" + obj.requestname + "&requestmark=" + obj.requestmark + "&requestid=" + obj.requestid;
		this.setState({
			loading: true
		});
		if (needCount) {
			const idArr = id ? id.split("_") : [];
			API.doDatasGet(paramsUrl, "browsername=" + params.fielddbtype + "&fieldId=" + idArr[0]).then((paramFields) => {
				if(this.state.isMain){
					//获取父组件联动值
					for (let i = 0; i < paramFields.length; i++) {
						let pf = paramFields[i];
						if (pf.viewtype == "1") {
							pf.value = wfDetail.doValueGet(dn, keyNum, pf.id);
						}
						else {
							const obje = document.getElementById("field" + pf.id);
							pf.value = obje?obje.value:""; //主表取dom
						}
						params[pf.searchname] = pf.value;
						//显示
						this.props.form.setFieldsValue({[pf.searchname]:pf.value});
					}
				}else{
					//获取弹出搜索框中值
					const obj = this.props.form.getFieldsValue();
					if (datasType == "custom") {
						for (let i = 0; i < searchs.length; i++) {
							if(!!obj[searchs[i].dataIndex]) params[searchs[i].dataIndex] = obj[searchs[i].dataIndex];
						}
					}
				}
				if(params == this.state.params) return
				//写进state
				//this.setState({params:params});
				//编写参数
				for (let key in params) {
					newParams += "&" + key + "=" + params[key];
				}
				return API.doDatasGet(countUrl, newParams);
			}).then(function (datas1) {
				//console.log("datas count:",datas1);
				that.setState({
					count: parseInt(datas1.count)
				});
				return API.doDatasGet(listUrl, newParams);
	    	}).then(function (datas) {
				//console.log("doDatasGet:", datas);
				if (datasType == "request") {
					that.setState({
						toPage: toPage,
						datas: datas,
						loading: false,
						columns: [],
						searchs: [],
						title: "请求",
						dataKey: "requestid"
					});
				}
				if (datasType == "custom") {
					//console.log("is in custom");
					//console.log("datas:",datas);
					//console.log("dataKey:",datas.datakey);
					that.setState({
						toPage: toPage,
						datas: datas.list,
						loading: false,
						columns: datas.head,
						searchs: datas.search,
						title: datas.title,
						dataKey: datas.datakey
					});
				}
				//console.log("datas:",datas);
	    	});
		}
		else {
			const idArr = id ? id.split("_") : [];
			API.doDatasGet(paramsUrl, "browsername=" + params.fielddbtype + "&fieldId=" + idArr[0]).then((paramFields) => {
				if(this.state.isMain){
					//获取父组件联动值
					for (let i = 0; i < paramFields.length; i++) {
						let pf = paramFields[i];
						if (pf.viewtype == "1") {
							pf.value = wfDetail.doValueGet(dn, keyNum, pf.id);
						}
						else {
							const obje = document.getElementById("field" + pf.id);
							pf.value = obje?obje.value:""; //主表取dom
						}
						params[pf.searchname] = pf.value;
					}
				}else{
					//获取弹出搜索框中值
					const obj = this.props.form.getFieldsValue();
					if (datasType == "custom") {
						for (let i = 0; i < searchs.length; i++) {
							if(!!obj[searchs[i].dataIndex]) params[searchs[i].dataIndex] = obj[searchs[i].dataIndex];
						}
					}
				}
				//编写参数
				for (let key in params) {
					newParams += "&" + key + "=" + params[key];
				}
				return API.doDatasGet(listUrl, newParams);
			}).then(function (datas) {
				if (datasType == "request") {
					that.setState({
						toPage: toPage,
						datas: datas,
						loading: false,
						columns: [],
						searchs: [],
						title: "请求",
						dataKey: "requestid"
					});
				}
				if (datasType == "custom") {
					that.setState({
						toPage: toPage,
						datas: datas.list,
						loading: false,
						columns: datas.head,
						searchs: datas.search,
						title: datas.title,
						dataKey: datas.datakey
					});
				}
				//console.log("datas:",datas);
			});
		}
	}
	ondblclick=()=>{
		if(typeof this.props.ondblclickCallBack === 'function'){
			// console.log('WeaList2');
			this.props.ondblclickCallBack();
		}
	}
	rowCls = (record, index)=>{
		// console.log('rowCls===',record,index);
		if(this.state.rowKey === record.key){
			return 'wea-browser-old-row-height-light';
		}
	}
	render() {
		let that = this;
		const {datasType} = this.props;
		const {datas, count, toPage, loading, ids, names, pageSize} = this.state;
		let {columns} = this.state;
		if (datasType == "request") {
			columns = [{
				title: '请求名称',
				dataIndex: 'requestname',
				key: 'requestname',
				render(text, record) {
					text = record.requestname + "(" + record.requestid + ")";
					return (
						<Tooltip title={text}><span>{text.length > 25 ? text.substring(0, 25) + "..." : text}</span></Tooltip>
					)
				}
			}, {
					title: '流程名称',
					dataIndex: 'workflowname',
					key: 'workflowname',
					render(text) {
						return (
							<Tooltip title={text}><span>{text.length > 25 ? text.substring(0, 25) + "..." : text}</span></Tooltip>
						)
					}
				}, {
					title: '创建人',
					dataIndex: 'creatername',
					key: 'creatername',
				}, {
					title: '创建时间',
					dataIndex: 'createdate',
					key: 'createdate',
				}, {
					title: '到达时间',
					dataIndex: 'receivedate',
					key: 'receivedate',
				}];
		}
		//console.log("columns:",columns);
		//console.log("datas:",datas);
		const {fieldhtmltype, type, fielddbtype, fieldId} = this.props;
		const pagination = {
			pageSize: pageSize,
			total: count,
			current: toPage,
			showSizeChanger: true,
			onChange(current) {
				//const params = "fieldhtmltype="+fieldhtmltype+"&type="+type+"&fielddbtype="+fielddbtype+"&fieldId="+fieldId;
				const params = { fieldhtmltype, type, fielddbtype, fieldId };
				that.getDatas(current, params, false);
			},
			onShowSizeChange(current,pageSize){
				that.setState({pageSize:pageSize});
			}
		};
		// console.log('columns',columns,'datas',datas);
		return (
			<div>
				{datasType == "request" ? this.renderRequestSearch() : ""}
				{datasType == "custom" ? this.renderCustomSearch() : ""}
				<div onDoubleClick={this.ondblclick} >
					<Table rowClassName={this.rowCls} pagination={pagination} dataSource={datas} columns={columns} size="middle" loading={loading} onRowClick={this.setData4Row.bind(this) }/>
				</div>
			</div>
		)
	}
	renderCustomSearch() {
		const { getFieldProps } = this.props.form;
		const {searchs} = this.state;
		let searchArr1 = [];
		let searchArr2 = [];
		let searchArr3 = [];
		function getSearchFormIteml(data) {
			return (
				<FormItem
					label={data.title + "："}
					labelCol={{ span: 10 }}
					wrapperCol={{ span: 14 }}>
					<Input {...getFieldProps(data.dataIndex, {
			        	initialValue: ""
					}) } />
				</FormItem>
			)
		}
		for (let i = 0; i < searchs.length; i++) {
			if (i % 3 == 0) { //dataIndex
				searchArr1[searchArr1.length] = getSearchFormIteml(searchs[i]);
			}
			if (i % 3 == 1) {
				searchArr2[searchArr2.length] = getSearchFormIteml(searchs[i]);
			}
			if (i % 3 == 2) {
				searchArr3[searchArr3.length] = getSearchFormIteml(searchs[i]);
			}
		}
		return (
			<Form horizontal className="advanced-search-form">
				<Row>
					<Col span="8">
						{searchArr1}
					</Col>
					<Col span="8">
						{searchArr2}
					</Col>
					<Col span="8">
						{searchArr3}
					</Col>
				</Row>
				<Row>
					<Col span="8" offset="16" style={{ textAlign: 'right' }}>
						<Button type="primary" htmlType="submit" onClick={this.doSubmit.bind(this) }>搜索</Button>
						<Button onClick={this.doClear.bind(this) }>清除条件</Button>
					</Col>
				</Row>
			</Form>
		)
	}
	renderRequestSearch() {
		const { getFieldProps } = this.props.form;
		return (
			<Form horizontal className="advanced-search-form">
				<Row>
					<Col span="8">
						<FormItem
							label="请求名称："
							labelCol={{ span: 10 }}
							wrapperCol={{ span: 14 }}>
							<Input {...getFieldProps('requestname', {
								initialValue: ""
							}) } />
						</FormItem>
					</Col>
					<Col span="8">
						<FormItem
							label="请求编码："
							labelCol={{ span: 10 }}
							wrapperCol={{ span: 14 }}>
							<Input {...getFieldProps('requestmark', {
								initialValue: ""
							}) } />
						</FormItem>
					</Col>
					<Col span="8">
						<FormItem
							label="请求ID："
							labelCol={{ span: 10 }}
							wrapperCol={{ span: 14 }}>
							<Input {...getFieldProps('requestid', {
								initialValue: ""
							}) } />
						</FormItem>
					</Col>
				</Row>
				<Row>
					<Col span="8" offset="16" style={{ textAlign: 'right' }}>
						<Button type="primary" htmlType="submit" onClick={this.doSubmit.bind(this) }>搜索</Button>
						<Button onClick={this.doClear.bind(this) }>清除条件</Button>
					</Col>
				</Row>
			</Form>
		)
	}
	doSubmit() {
		const {fieldhtmltype, type, fielddbtype, fieldId, datasType} = this.props;
		//console.log("doSubmit:",obj);
		//const params = "fieldhtmltype="+fieldhtmltype+"&type="+type+"&fielddbtype="+fielddbtype+"&fieldId="+fieldId
		const params = { fieldhtmltype, type, fielddbtype, fieldId };
		this.setState( {isMain: false} );
		this.getDatas(1, params, true);
	}
	doClear() {
		const { setFieldsValue } = this.props.form;
		const {datasType} = this.props;
		const {columns,searchs} = this.state;
		if ("request" == datasType) {
			setFieldsValue({
				requestname: "",
				requestmark: "",
				requestid: ""
			});
		}
//		console.log('columns',columns);
//		console.log('searchs',searchs);
		if ("custom" == datasType) {
//			for (let i = 0; i < columns.length; i++) {
//				if (columns[i].dataIndex && columns[i].dataIndex != "") {
//					setFieldsValue({[columns[i].dataIndex]:''});
//				}
//			}
			for (let i = 0; i < searchs.length; i++) {
				if (searchs[i].dataIndex && searchs[i].dataIndex != "") {
					setFieldsValue({[searchs[i].dataIndex]:''});
				}
			}
		}
	}
	setData4Row(record, index) {
		const {searchs, dataKey, columns} = this.state;
		const {isMult, datasType} = this.props;
		let {ids, names} = this.state;
		// console.log("setData4Row:",record,index);
		//console.log("dataKey1:",dataKey);
		if (!isMult) {
			ids = new Array();
			names = new Array();
		}
		let recordId = "";
		if (dataKey && dataKey != "")
			eval("recordId=record." + dataKey);
		let find = false;
		for (let i = 0; i < ids.length && !find; i++) {
			if (ids[i] == recordId) {
				find = true;
			}
		}
		//console.log("recordId:",recordId);
		//console.log("dataKey:",dataKey);
		if ("request" == datasType) {
			if (!find) {
				ids.push(recordId);
				names.push(record.requestname + "(" + recordId + ")");
				this.props.setData(ids.join(","), names.join(","));
			}
		}
		if ("custom" == datasType) {
			if (!find) {
				let dataIndexType = "";
				for (let i = 0; i < columns.length && dataIndexType == ""; i++) {
					if (columns[i].dataIndexType != "") {
						dataIndexType = columns[i].dataIndexType;
					}
				}
				let dataIndexValue = "";
				eval("dataIndexValue = record." + dataIndexType);
				ids.push(recordId);
				names.push(dataIndexValue);
				//console.log("recordId:",recordId);
				//console.log("dataIndexValue:",dataIndexValue);
				this.props.setData(ids.join(","), names.join(","));
				//ids.push(recordId);
				//names.push(record.requestname+"("+recordId+")");
				//this.props.setData(ids.join(","),names.join(","));
			}
		}
		//console.log("test");
		//this.props.setData(record.id,names);
		this.setState({rowKey:record.key});
	}
}

WeaList = createForm()(WeaList);

export default WeaList;

/*




componentDidMount() {
		let that = this;
		const {actionUrl,fieldId} = this.props;
		const params = "fieldId="+fieldId;
		doDatasGet(actionUrl,params).then(function(datas) {
			console.log("componentDidMount:",datas);
		});
	}

*/